import { OrganizationModel } from '@/pages/person/data';
import { permissionResponse } from '@/pages/system/data';
import { MenuDataItem } from '@ant-design/pro-components';
import { TreeDataNode } from 'antd';

export function transformTree(flatArray: permissionResponse[]): TreeDataNode[] {
  const tree: TreeDataNode[] = [];
  const childrenMap: { [key: string]: TreeDataNode[] } = {};

  flatArray.forEach((node) => {
    const transformedNode: TreeDataNode = {
      title: node.displayName,
      key: node.name,
    };

    if (node.parentName) {
      if (!childrenMap[node.parentName]) {
        childrenMap[node.parentName] = [];
      }
      childrenMap[node.parentName].push(transformedNode);
    } else {
      tree.push(transformedNode);
    }

    if (!childrenMap[node.name]) {
      childrenMap[node.name] = [];
    }
    transformedNode.children = childrenMap[node.name];
  });

  return tree;
}

function insertPath(root: any, path: string[], index: number) {
  if (index >= path.length) return;

  const segment = path[index];
  if (!root[segment]) {
    root[segment] = {};
  }

  insertPath(root[segment], path, index + 1);
}

function convertToTreeNodes(root: any, key: string): TreeDataNode {
  const childrenKeys = Object.keys(root);
  const node: TreeDataNode = { title: key, key: key };

  if (childrenKeys.length > 0) {
    node.children = childrenKeys.map((childKey, index) =>
      convertToTreeNodes(root[childKey], `${key}-${index}`),
    );
  }

  return node;
}

export function transstrToTree(data: string[]): TreeDataNode[] {
  const root: any = {};

  data.forEach((path) => {
    const segments = path.split('.');
    insertPath(root, segments, 0);
  });

  return Object.keys(root).map((key) => convertToTreeNodes(root[key], `0-${key}`));
}

export function filterMenuItems(menuItems: MenuDataItem[], names: string[]): MenuDataItem[] {
  return menuItems.reduce<MenuDataItem[]>((acc, item) => {
    if (item.name === 'dashboard') acc.push({ ...item });
    else {
      const shouldInclude = item.name && names.includes(item.name);
      const filteredChildren = item.children ? filterMenuItems(item.children, names) : [];
      if (shouldInclude || filteredChildren.length > 0) {
        acc.push({ ...item, children: filteredChildren });
      }
    }
    return acc;
  }, []);
}

// 构建一个字典方便查找每个节点的子节点
export function buildTree(data: OrganizationModel.organizationResponse[]): TreeDataNode[] {
  const map: { [key: string]: TreeDataNode } = {};
  const roots: TreeDataNode[] = [];
  data.forEach(({ code, name, parentCode }) => {
    if (!code || !name) {
      throw new Error(
        `Invalid node: code and name are required. Received code: ${code}, name: ${name}`,
      );
    }
    const node: TreeDataNode = { title: name, key: code, children: [] };
    map[code] = node;

    if (parentCode) {
      if (!map[parentCode]) {
        map[parentCode] = { title: '', key: parentCode, children: [] };
      }
      map[parentCode].children!.push(node);
    } else {
      roots.push(node);
    }
  });

  // 移除没有子节点的空数组
  const removeEmptyChildren = (node: TreeDataNode) => {
    if (node.children && node.children.length === 0) {
      delete node.children;
    } else if (node.children) {
      node.children.forEach(removeEmptyChildren);
    }
  };
  roots.forEach(removeEmptyChildren);
  return roots;
}
